package com.address.server;



import com.google.gson.Gson;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.address.AddressTool;
import org.address.DataTable;
import org.address.OrderRecognition;
import org.address.entity.StandardAddress;
import org.address.license.License;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class OrderParserServer {
    License ls =new License();
    static AddressTool ss = new AddressTool();
//    static AddressTool ss = new AddressTool("localhost",6379);
    static DataTable as = new DataTable();
    static Gson gson = new Gson();
    static OrderRecognition recog = new OrderRecognition();


    public static void main(String[] args) throws Exception {
        recog.addName("两只蝴蝶");
        recog.addName("打工人打工魂");

        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/order", new MyHandler());
        server.setExecutor(null);
        System.out.println("Starting server on port: 8000");
        server.start();
//        Thread.sleep(100000);
//        server.stop(1);
    }

    static class MyHandler implements HttpHandler {
        public void handle(HttpExchange t) throws IOException {
            String response = "{\"response\":\"快递订单解析错误\"}";

            String parmsStr = t.getRequestURI().getQuery();
            if(!parmsStr.isEmpty()){
                String[] parms = parmsStr.split("&");
                if(parms.length>0){
                    HashMap<String,String> keys = new HashMap<>();
                    for (String urlKey:parms){
                        if(urlKey.contains("=")){
                            String[] kv = urlKey.split("=");
                            keys.put(kv[0].toLowerCase(),kv[1]);
                        }
                    }
                    if(keys.containsKey("orderinfo")){
//                        System.out.println(keys);
                        response = gson.toJson(recog.recognition(keys.get("orderinfo")));
                    }
                }
            }

//            System.out.println(t.getRequestURI().getQuery());

            t.getResponseHeaders().set("Content-Type", "application/json");
//            t.getResponseHeaders().set("Content-Type", "text/html;charset=utf-8");
            t.sendResponseHeaders(200, 0);
            OutputStream os = t.getResponseBody();
            byte[] b = response.getBytes();
            for (int i = 0; i < b.length; i++) {
                os.write(b[i]);
            }
            os.close();
        }
    }



}
